<?php

namespace app\admin\controller\article;

use app\admin\model\Category;
use app\common\controller\Backend;
use app\common\library\Push;
use jrk\Tool;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 文章管理
 *
 * @icon fa fa-circle-o
 */
class Articles extends Backend
{

    /**
     * Articles模型对象
     * @var \app\admin\model\article\Articles
     */
    protected $model = null;

    protected $noNeedRight = ['searchlist'];

    public function _initialize()
    {
        parent::_initialize();
        $this->modelValidate = true;
        $this->model = new \app\admin\model\article\Articles;
        $this->view->assign("isTuiList", $this->model->getIsTuiList());
        $this->view->assign("isRecommendList", $this->model->getIsRecommendList());
        $this->view->assign("isTopList", $this->model->getIsTopList());
        $this->view->assign("isShowList", $this->model->getIsShowList());
        $this->view->assign("statusList", $this->model->getStatusList());

        $this->assignconfig('check_tuisong', $this->auth->check('article/articles/tuisong'));
        $this->assignconfig('check_delete', $this->auth->check('article/articles/check_delete'));
    }


    public function searchlist()
    {
        $result = $this->model->banklist();
        return json($result['arr']);
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->withJoin(['category'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->withJoin(['category'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        $Category= Category::where('status','1')->select();

        $this->view->assign('category', $Category);

        return $this->view->fetch();
    }


    //移动文章栏目
    public function move(){
        if ($this->request->isAjax()) {
            $data=$this->request->post();
            //dd($data);
            $ids=@explode(',',$data['ids']);
            $result=$this->model->where('id','in',$ids)->save(['category_id'=>$data['category_id']]);

            if ($result !== false) {
                $this->success('移动成功');
            }
            $this->error('移动失败');
        }
    }



    //百度推送
    public function tuisong()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->post("id", 0);
            $row = $this->model->get($id);
            if (!$row) {
                $this->error(__('No Results were found'));
            }

            $urls = $this->sysConfig['basic']['site_url'] . $row['url'];
            if (!Tool::is_url($this->sysConfig['basic']['site_url'])) {
                $this->error("请先配置正确的网站域名");
            }
            if (!$row['url']) {
                $this->error("URL不能为空");
            }
            $aurl = [$urls];
            $result = Push::init(['type' => 'zhanzhang'])->realtime($aurl);
            if ($result) {
                $data = Push::init()->getData();

                $this->model->where("id", $id)->update(['is_tui' => '1']);

                $this->success("推送成功", null, $data);
            } else {
                $this->error("推送失败：" . Push::init()->getError());
            }
        }
    }


    //推送删除
    public function check_delete()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->post("id", 0);
            $row = $this->model->get($id);
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            $urls = $this->sysConfig['basic']['site_url'] . $row['url'];

            if (!Tool::is_url($this->sysConfig['basic']['site_url'])) {
                $this->error("请先配置正确的网站域名");
            }
            if (!$row['url']) {
                $this->error("URL不能为空");
            }
            $aurl = [$urls];
            $result = Push::init(['type' => 'zhanzhang'])->delete($aurl);
            if ($result) {
                $data = Push::init()->getData();

                $this->model->where("id", $id)->update(['is_tui' => '2']);

                $this->success("删除推送成功", null, $data);
            } else {
                $this->error("删除推送失败：" . Push::init()->getError());
            }
        }
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                $params['content'] = htmlspecialchars_decode($params['content']);
                if (empty($params['description'])) {
                    $params['description'] = Tool::str_cut($params['content'], 100);
                }
                $this->model->startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        validate($validate)->scene($this->modelSceneValidate ? 'edit' : $name)->check($params);
                    }
                    $result = $this->model->save($params);
                    $this->model->commit();
                } catch (ValidateException $e) {
                    $this->model->rollback();
                    $this->error($e->getMessage());
                } catch (\PDOException $e) {
                    $this->model->rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    $this->model->rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if ($params['origin'] == '原创') {
                        $this->model->where("id", $this->model->id)->save(['url' => '/show/' . base64_encode($this->model->id)]);
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                $params['content'] = htmlspecialchars_decode($params['content']);
                if (empty($params['description'])) {
                    $params['description'] = Tool::str_cut($params['content'], 100);
                }
                $this->model->startTrans();

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace('\\model\\', '\\validate\\', get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? $name : $this->modelValidate;
                        $pk = $row->getPk();
                        if (!isset($params[$pk])) {
                            $params[$pk] = $row->$pk;
                        }
                        validate($validate)->scene($this->modelSceneValidate ? 'edit' : $name)->check($params);
                    }
                    $result = $row->save($params);
                    $this->model->commit();
                } catch (ValidateException $e) {
                    $this->model->rollback();
                    $this->error($e->getMessage());
                } catch (\PDOException $e) {
                    $this->model->rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    $this->model->rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if ($params['origin'] == '原创') {
                        $this->model->where("id", $ids)->save(['url' => '/show/' . base64_encode($ids)]);
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign('row', $row);

        return $this->view->fetch();
    }

}
